package sdk

import (
	"encoding/json"
	"fmt"
	"math/rand"
	"peilian-api/app/global/variable"
	"time"

	openapi "github.com/alibabacloud-go/darabonba-openapi/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v2/client"
	"github.com/alibabacloud-go/tea/tea"
	"go.uber.org/zap"
)

type SmsService struct{}

func (m *SmsService) SendCode(phone string) bool {
	// 1. 生成一个验证码
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	// 获取配置文件
	// 2. 调用阿里云sdk，完成发送
	client, _err := m.CreateClient(tea.String(variable.Config.AliMsg.AccesskeyId), tea.String(variable.Config.AliMsg.AccesskeySecret))
	if _err != nil {
		fmt.Println(_err.Error())
		return false
	}

	bCode, _ := json.Marshal(map[string]interface{}{
		"code": code,
	})
	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		PhoneNumbers:  tea.String(phone),
		TemplateCode:  tea.String(variable.Config.AliMsg.TemplateCode),
		SignName:      tea.String(variable.Config.AliMsg.SignName),
		TemplateParam: tea.String(string(bCode)),
	}
	// 复制代码运行请自行打印 API 的返回值
	sendSmsResponse, _ := client.SendSms(sendSmsRequest)
	if *sendSmsResponse.Body.Code == "OK" {
		zap.S().Infof("发送给手机号： %s 的短信验证码成功【%s】", phone, code)
		// 将验证码保存进redis数据库
		err := variable.DB.Redis.Set(phone, code, 2*time.Minute).Err()

		if err != nil {
			fmt.Sprintf("发送失败：%s-%s", phone, code)
			fmt.Println(err)
			return false
		}
		return true
	}

	return false
}

func (m *SmsService) CreateClient(accessKeyId *string, accessKeySecret *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 您的AccessKey ID
		AccessKeyId: accessKeyId,
		// 您的AccessKey Secret
		AccessKeySecret: accessKeySecret,
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

/**
 *  @param phone string
 *  @return true | false
 */
func SendSmsCode(phone string) bool {
	sms := new(SmsService)
	return sms.SendCode(phone)
}
